package com.tensquare.user.controller;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import util.JwtUtil;

/**
 * 控制器层.
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

  @Autowired private UserService userService;
  @Autowired private RedisTemplate redisTemplate;
  @Resource private JwtUtil jwtUtil;

  /** 更新好友的 粉丝数 和 自己的关注数. */
  @PutMapping("/{userid}/{friendid}/{x}")
  public void updateFanscountAndFollowcount(
      @PathVariable String userid, @PathVariable String friendid, @PathVariable Integer x) {
    userService.updateFanscountAndFollowcount(x, userid, friendid);
  }

  @PostMapping("/login")
  public Result login(@RequestBody User user) {
    user = userService.login(user);
    if (user == null) {
      return new Result(false, StatusCode.LOGINERROR, "登录失败");
    }

    String token = jwtUtil.createJWT(user.getId(), user.getEmail(), "user");

    /** 将权限和token返回给前端. */
    Map<String, Object> map = new HashMap<>();
    map.put("role", "user");
    map.put("token", token);
    return new Result(true, StatusCode.OK, "登录成功", map);
  }

  /** 发送短信验证码. */
  @PostMapping("/sendsms/{mobile}")
  public Result sendSms(@PathVariable String mobile) {
    userService.sendSms(mobile);
    return new Result(true, StatusCode.OK, "发送成功");
  }

  /** 发送邮箱验证码. */
  @PostMapping("/sendMail/{mail}")
  public Result sendMail(@PathVariable String mail) {
    userService.sendMail(mail);
    return new Result(true, StatusCode.OK, "发送成功");
  }

  /** 用户注册（邮件验证）. */
  @PostMapping("/register/{code}")
  private Result register(@PathVariable String code, @RequestBody User user) {
    String emailCode = (String) redisTemplate.opsForValue().get("code" + user.getEmail());
    if (StringUtils.isBlank(emailCode)) {
      return new Result(false, StatusCode.ERROR, "请先获取验证码");
    }
    if (!code.equals(emailCode)) {
      return new Result(false, StatusCode.ERROR, "验证码错误");
    }
    userService.add(user);
    return new Result(false, StatusCode.ERROR, "注册成功!");
  }

  //  /** 用户注册（手机号验证）. */
  //  @PostMapping("/register/{code}")
  //  private Result regist(@PathVariable String code, @RequestBody User user) {
  //    String smsCode = (String) redisTemplate.opsForValue().get("checkcode:" + user.getMobile());
  //    if (StringUtils.isBlank(smsCode)) {
  //      return new Result(false, StatusCode.ERROR, "请先获取验证码");
  //    }
  //    if (!code.equals(smsCode)) {
  //      return new Result(false, StatusCode.ERROR, "验证码错误");
  //    }
  //    user.setId(idWorker.nextId() + "");
  //    user.setFollowcount(0); // 关注数
  //    user.setFanscount(0); // 粉丝数
  //    user.setOnline(0L); // 在线时长
  //    user.setRegdate(new Date()); // 注册日期
  //    user.setUpdatedate(new Date()); // 更新日期
  //    user.setLastdate(new Date()); // 最后登陆日期
  //    userService.add(user);
  //    return new Result(false, StatusCode.ERROR, "注册成功!");
  //  }

  /**
   * 删除，必须有admin权限才能删除. token 放在了请求消息头里面
   *
   * @param id
   */
  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  public Result delete(@PathVariable String id) {
    userService.deleteById(id);
    return new Result(true, StatusCode.OK, "删除成功");
  }

  /**
   * 查询全部数据
   *
   * @return
   */
  @RequestMapping(method = RequestMethod.GET)
  public Result findAll() {
    return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
  }

  /**
   * 根据ID查询
   *
   * @param id ID
   * @return
   */
  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  public Result findById(@PathVariable String id) {
    User user = userService.findById(id);
    return new Result(true, StatusCode.OK, "查询成功", user);
  }

  /**
   * 分页+多条件查询
   *
   * @param searchMap 查询条件封装
   * @param page 页码
   * @param size 页大小
   * @return 分页结果
   */
  @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
  public Result findSearch(
      @RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
    Page<User> pageList = userService.findSearch(searchMap, page, size);
    return new Result(
        true,
        StatusCode.OK,
        "查询成功",
        new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
  }

  /**
   * 根据条件查询
   *
   * @param searchMap
   * @return
   */
  @RequestMapping(value = "/search", method = RequestMethod.POST)
  public Result findSearch(@RequestBody Map searchMap) {
    return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
  }

  /**
   * 增加
   *
   * @param user
   */
  @RequestMapping(method = RequestMethod.POST)
  public Result add(@RequestBody User user) {
    userService.add(user);
    return new Result(true, StatusCode.OK, "增加成功");
  }

  /**
   * 修改
   *
   * @param user
   */
  @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  public Result update(@RequestBody User user, @PathVariable String id) {
    user.setId(id);
    userService.update(user);
    return new Result(true, StatusCode.OK, "修改成功");
  }
}
